<template>
  <div class="order-container">
    <!-- 搜索区域 -->
    <div class="search-card">
      <el-form :inline="true" :model="orderSearchModel" class="demo-form-inline" ref="orderSearchForm">
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="orderSearchModel.orderNo" placeholder="请输入订单号" :prefix-icon="Search" class="search-input" />
        </el-form-item>
        <el-form-item label="会员编号" prop="memberId">
          <el-input v-model="orderSearchModel.memberId" placeholder="请输入会员编号" class="search-input" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="orderSearchModel.status" clearable style="width: 120px" class="search-select">
            <el-option label="全部" value="" />
            <el-option label="待支付" value="待支付" />
            <el-option label="已支付" value="已支付" />
            <el-option label="已发货" value="已发货" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付时间" prop="payTimeRange">
          <el-date-picker type="daterange" v-model="orderSearchModel.payTimeRange" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss" class="search-date" />
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <el-button type="primary" :icon="CirclePlus" @click="add" class="action-btn add-btn">新增</el-button>
      <el-button type="primary" :icon="Edit" @click="edit" class="action-btn edit-btn">修改</el-button>
      <el-button type="danger" :icon="Delete" @click="remove" class="action-btn delete-btn">删除</el-button>
      <el-button type="primary" :icon="Search" @click="searchAll()" class="action-btn search-btn">查询</el-button>
      <el-button type="primary" :icon="RefreshRight" @click="reset" class="action-btn reset-btn">重置</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table :data="orders" height="100%" style="width: 100%" stripe border class="table-grid" @row-click="tblRowClick" ref="tblRef" :row-class-name="tableRowClassName">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" width="80" fixed />
        <el-table-column prop="orderNo" label="订单号" width="160" />
        <el-table-column prop="memberId" label="会员编号" width="100" />
        <el-table-column prop="totalPay" label="订单总价" width="100">
          <template #default="scope">¥{{ Number(scope.row.totalPay).toFixed(2) }}</template>
        </el-table-column>
        <el-table-column prop="payType" label="支付方式" width="100" />
        <el-table-column prop="payNo" label="支付宝交易号" width="180" />
        <el-table-column prop="payTime" label="支付时间" width="160" />
        <el-table-column prop="status" label="订单状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status==='已完成'?'success':scope.row.status==='已取消'?'danger':'info'">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="receiverName" label="收货人" width="120" />
        <el-table-column prop="receiverPhone" label="收货人手机号" width="140" />
        <el-table-column prop="receiverAddrDetail" label="收货地址" width="200" />
        <el-table-column prop="orderComment" label="订单备注" width="180" />
        <el-table-column prop="description" label="平台备注" width="180" />
        <el-table-column label="操作" width="160" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click.stop="editRow(scope.row)" class="table-btn edit">编辑</el-button>
            <el-button type="danger" size="small" @click.stop="removeRow(scope.row)" class="table-btn delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination v-model:current-page="orderPi.pageNo" v-model:page-size="orderPi.pageSize" :page-sizes="[10, 20, 30, 40,50]" layout="total, sizes, prev, pager, next, jumper" :total="orderPi.total" class="order-pi" @change="orderPiChange" background />
    </div>

    <!-- 添加/修改对话框 -->
    <el-dialog v-model="orderDlgShow" :title="orderDlgTitle" width="700px" :close-on-click-modal="false" draggable show-close align-center @close="resetOrderForm" class="order-dialog">
      <el-form label-width="120" label-position="right" :model="orderModel" ref="orderForm" :rules="rules" class="order-form">
        <el-row>
          <el-col :span="12">
            <el-form-item label="会员编号" prop="memberId">
              <el-input placeholder="请输入会员编号" v-model="orderModel.memberId" />
            </el-form-item>
            <el-form-item label="支付方式" prop="payType">
              <el-select v-model="orderModel.payType" placeholder="请选择支付方式">
                <el-option label="支付宝" value="支付宝" />
                <el-option label="微信" value="微信" />
                <el-option label="银行卡" value="银行卡" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单状态" prop="status" v-if="mode==='edit'">
              <el-select v-model="orderModel.status" placeholder="请选择订单状态">
                <el-option label="待支付" value="待支付" />
                <el-option label="已支付" value="已支付" />
                <el-option label="已发货" value="已发货" />
                <el-option label="已完成" value="已完成" />
                <el-option label="已取消" value="已取消" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货人" prop="receiverName">
              <el-input placeholder="请输入收货人姓名" v-model="orderModel.receiverName" />
            </el-form-item>
            <el-form-item label="收货人手机号" prop="receiverPhone">
              <el-input placeholder="请输入收货人手机号" v-model="orderModel.receiverPhone" />
            </el-form-item>
            <el-form-item label="收货地址" prop="receiverAddrDetail">
              <el-input placeholder="请输入收货地址" v-model="orderModel.receiverAddrDetail" />
            </el-form-item>
            <el-form-item label="订单备注" prop="orderComment">
              <el-input placeholder="请输入订单备注" v-model="orderModel.orderComment" />
            </el-form-item>
            <el-form-item label="平台备注" prop="description">
              <el-input placeholder="请输入平台备注" v-model="orderModel.description" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="doSubmit" class="dialog-btn confirm">确定</el-button>
          <el-button @click="orderDlgShow=false" class="dialog-btn cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.order-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}
</style>

<script setup>
import { onMounted, ref, reactive, toRaw, nextTick } from "vue"
import { CirclePlus, Delete, Edit, Search, RefreshRight } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash";
import { getOrders,deleteOrder,updateOrder,createOrder} from '@/api/order.js';
import api from '@/util/api';

onMounted(() => {
  searchAll();
});

let orders = ref([]);
let orderPi = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
});
let orderSearchModel = ref({
  orderNo: null,
  memberId: null,
  status: null,
  payTimeRange: []
});
let orderSearchForm = ref();
let orderDlgTitle = ref("新增订单");
let orderDlgShow = ref(false);
let orderModel = ref({
  orderNo: '',
  memberId: '',
  payType: '',
  status: '',
  receiverName: '',
  receiverPhone: '',
  receiverAddrDetail: '',
  orderComment: '',
  description: ''
});
let mode = "add";
let tblRef = ref();

async function searchAll(pageNo = 1, pageSize = 10) {
  let params = toRaw(orderSearchModel.value);
  if (params.payTimeRange && params.payTimeRange.length === 2) {
    params.payTimeFrom = params.payTimeRange[0].replace(' ', 'T');
params.payTimeTo = params.payTimeRange[1].replace(' ', 'T');
    delete params.payTimeRange;
  }
  params.pageNo = pageNo;
  params.pageSize = pageSize;
  let resp = await getOrders(params);
  orders.value = resp.data.records.filter(order => order.isDel === 1);
  orderPi.pageNo = resp.data.current;
  orderPi.pageSize = resp.data.size;
  orderPi.total = resp.data.total;
}

function orderPiChange(pageNo, pageSize) {
  searchAll(pageNo, pageSize);
}

function reset() {
  orderSearchForm.value.resetFields();
  searchAll();
}

function tblRowClick(row) {
  tblRef.value.toggleRowSelection(row);
}

function remove() {
  let rows = tblRef.value.getSelectionRows();
  if (!rows || rows.length === 0) {
    ElMessage({ message: '请选中要删除的数据', type: 'warning' })
  } else {
    ElMessageBox.confirm('是否确认删除', '警告', {
      confirmButtonText: '是', cancelButtonText: '否', type: 'warning',
    }).then(() => {
      let ids = rows.map(row => row.id)
      removeByIds(ids);
    }).catch(() => {
      ElMessage({ type: 'info', message: '已取消删除' })
    })
  }
}
function removeRow(row) {
  ElMessageBox.confirm('是否确认删除', '警告', {
    confirmButtonText: '是', cancelButtonText: '否', type: 'warning',
  }).then(() => {
    removeByIds([row.id]);
  }).catch(() => {
    ElMessage({ type: 'info', message: '已取消删除' })
  })
}
async function removeByIds(ids) {
  let resp = await deleteOrder(ids);
  if (resp.success) {
    ElMessage.success("删除成功,共删除" + resp.data + "条数据")
    searchAll();
  } else {
    ElMessage({
      type: 'info',
      message: '删除失败',
    })
  }
}
function add() {
  orderDlgTitle.value = "新增订单";
  orderDlgShow.value = true;
  mode = "add";
  orderModel.value = {
    memberId: '',
    payType: '',
    status: '待支付',
    receiverName: '',
    receiverPhone: '',
    receiverAddrDetail: '',
    orderComment: '',
    description: ''
  }
}
function doSubmit() {
  if (mode === "add") {
    submitAdd();
  } else {
    submitEdit();
  }
}
function submitAdd() {
  let params = toRaw(orderModel.value);
  orderForm.value.validate(valid => {
    if (valid) {
      let resp = createOrder(params).then(resp => {
        if (resp.success) {
          console.log(resp)
          orderDlgShow.value = false;
          searchAll();
          ElMessage.success("新增成功")
        } else {
          ElMessage.error(resp.msg || "新增失败")
        }
      }).catch(resp => {
        ElMessage.error(resp.msg || "新增失败")
      });
    } else {
      ElMessage.error("请填写必填项")
    }
  })
}
let orderForm = ref();
function resetOrderForm() {
  orderForm.value.resetFields();
}
function edit() {
  let rows = tblRef.value.getSelectionRows();
  if (!rows || rows.length === 0) {
    ElMessage.warning("请选择要修改的行");
  } else if (rows.length > 1) {
    ElMessage.warning("只能选择一行进行修改");
  } else {
    orderDlgShow.value = true;
    orderDlgTitle.value = "修改订单信息";
    mode = "edit";
    nextTick(() => {
      orderModel.value = cloneDeep(toRaw(rows[0]));
    });
  }
}
async function submitEdit() {
  let params = toRaw(orderModel.value);
   let resp = await updateOrder(params);
  if (resp.success) {
    memberDlgShow.value = false;
    searchAll(memberPi.pageNo, memberPi.pageSize);
    ElMessage.success("修改成功")
  }
}
function editRow(row) {
  orderDlgShow.value = true;
  orderDlgTitle.value = "修改订单信息";
  mode = "edit";
  nextTick(() => {
    orderModel.value = cloneDeep(toRaw(row));
  });
}
const rules = {
  orderNo: [ { required: true, message: '请输入订单号', trigger: 'blur' } ],
  receiverName: [ { required: true, message: '请输入收货人姓名', trigger: 'blur' } ],
  receiverPhone: [ { required: true, message: '请输入收货人手机号', trigger: 'blur' } ]
}
function tableRowClassName() {
  return 'tableRowClassName';
}
</script>
